import 'dart:convert';

import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/attention_anchor_request.dart';
import 'package:elephant_fish/http/request/attention_room_request.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/person_contribute_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/http/request/user_join_home_request.dart';
import 'package:elephant_fish/model/person_contribute_entity.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/page/update_info_page.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/IconTextButton.dart';
import 'package:elephant_fish/widget/person_contribute.dart';
import 'package:elephant_fish/widget/slide_banner.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class UserPersonalInterfacePage extends StatefulWidget {
  final UserInfoEntity userInfoEntity;
  final int userId;

  const UserPersonalInterfacePage({
    Key key,
    this.userInfoEntity,
    this.userId,
  }) : super(key: key);

  @override
  _UserPersonalInterfacePageState createState() =>
      _UserPersonalInterfacePageState();
}

class _UserPersonalInterfacePageState extends State<UserPersonalInterfacePage> {
  bool isFollowed = false;
  UserInfoEntity myInfo;
  bool isAuth = true;
  bool isRefresh = false;
  ScrollController _scrollController = ScrollController();
  List<PersonContributeEntity> personContributeEntity;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getMyUserInfo();
    getPersonContribute();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      body:
         Column(
          children: [
            Container(
              width: size.width,
              height: SizeUtil.px(690),
              decoration: BoxDecoration(
                  // image: DecorationImage(image: NetworkImage(myInfo== null ? 'https://img1.baidu.com/it/u=2487750508,1671274011&fm=26&fmt=auto&gp=0.jpg' :myInfo.avatar == null ? 'https://img1.baidu.com/it/u=2487750508,1671274011&fm=26&fmt=auto&gp=0.jpg' :'http://119.28.131.94:82' + myInfo.avatar),fit: BoxFit.cover)
                  ),
              child: Stack(
                children: [
                  myInfo != null
                      ? SlideBanner(photoWall: myInfo.photoWall)
                      : Image.network(
                          'https://img1.baidu.com/it/u=2487750508,1671274011&fm=26&fmt=auto&gp=0.jpg'),
                  Align(
                    alignment: Alignment.topLeft,
                    child: Padding(
                      padding: EdgeInsets.only(
                          left: SizeUtil.px(50), top: SizeUtil.px(68)),
                      child: GestureDetector(
                        child: Icon(
                          Icons.arrow_back_ios,
                          size: SizeUtil.px(32),
                          color: Color(0xfff3f3f3),
                        ),
                        onTap: () {
                          if (isRefresh) {
                            Navigator.pop(context);
                          } else {
                            Navigator.of(context).pop("refresh");
                          }
                        },
                      ),
                    ),
                  ),
                  isAuth
                      ? Align(
                          alignment: Alignment.topRight,
                          child: Padding(
                            padding: EdgeInsets.only(
                                right: SizeUtil.px(27), top: SizeUtil.px(68)),
                            child: InkWell(
                              child: Container(
                                width: SizeUtil.px(50),
                                height: SizeUtil.px(50),
                                child: Image.asset(
                                    'assets/images/user_personal_edit.png'),
                              ),
                              onTap: () {
                                // Navigator.pushNamed(context, '/userPersonalInterface');
                                Navigator.of(context)
                                    .push(MaterialPageRoute(
                                        builder: (context) =>
                                            UpdateInfoPage(arguments: {
                                              'userInfo': widget.userInfoEntity
                                            })))
                                    .then((value) =>
                                        {isRefresh = true, getMyUserInfo()});
                              },
                            ),
                          ))
                      : Align(
                          alignment: Alignment.topRight,
                          child: Padding(
                            padding: EdgeInsets.only(
                                right: SizeUtil.px(27), top: SizeUtil.px(68)),
                            child: Container(
                              width: SizeUtil.px(50),
                              height: SizeUtil.px(50),
                              child: Image.asset(
                                  'assets/images/personal_interface_share.png'),
                            ),
                          ))
                ],
              ),
            ),
            SizedBox(
              height: SizeUtil.px(17),
            ),
            Row(
              children: [
                SizedBox(
                  width: SizeUtil.px(27),
                ),
                Text(
                  myInfo == null ? '' : myInfo.nickname,
                  style: TextStyle(
                      fontSize: SizeUtil.px(45), color: Color(0xfff3f3f3)),
                ),
                SizedBox(
                  width: SizeUtil.px(8),
                ),
                myInfo == null
                    ? Container(
                        width: 0,
                        height: 0,
                      )
                    : myInfo.sex == 2
                        ? Image(
                            image:
                                AssetImage('assets/images/personal_girl.png'),
                            width: SizeUtil.px(28.71),
                            height: SizeUtil.px(28.71),
                          )
                        : Image(
                            image: AssetImage('assets/images/personal_boy.png'),
                            width: SizeUtil.px(28.71),
                            height: SizeUtil.px(28.71),
                          )
              ],
            ),
            SizedBox(
              height: SizeUtil.px(17),
            ),
            Row(
              children: [
                SizedBox(
                  width: SizeUtil.px(27),
                ),
                Text(
                  myInfo == null ? '' : 'ID:' + myInfo.idNumber,
                  style: TextStyle(
                      fontSize: SizeUtil.px(22), color: Color(0xfff3f3f3)),
                ),
                SizedBox(
                  width: SizeUtil.px(17),
                ),
                Container(
                  width: SizeUtil.px(62),
                  height: SizeUtil.px(30),
                  decoration: BoxDecoration(
                    borderRadius:
                        BorderRadius.all(Radius.circular(SizeUtil.px(29))),
                    border: Border.all(
                        width: SizeUtil.px(1), color: Color(0xffffffff)),
                  ),
                  child: InkWell(
                    child: Center(
                      child: Text(
                        '复制',
                        style: TextStyle(
                            fontSize: SizeUtil.px(19),
                            color: Color(0xfff3f3f3)),
                      ),
                    ),
                    onTap: () {
                      Clipboard.setData(ClipboardData(text: myInfo.idNumber));
                      TxUtils.showToast('已复制', context);
                    },
                  ),
                )
              ],
            ),
            SizedBox(
              height: SizeUtil.px(21),
            ),
            Row(
              children: [
                SizedBox(
                  width: SizeUtil.px(27),
                ),
                Image(
                  image: AssetImage('assets/images/address.png'),
                  width: SizeUtil.px(18.96),
                  height: SizeUtil.px(23.44),
                ),
                SizedBox(
                  width: SizeUtil.px(4),
                ),
                Text(
                  '好像在火星',
                  style: TextStyle(
                      fontSize: SizeUtil.px(22), color: Color(0xfff3f3f3)),
                ),
              ],
            ),
            SizedBox(
              height: SizeUtil.px(4),
            ),
            Row(
              children: [
                SizedBox(
                  width: SizeUtil.px(27),
                ),
                Text(
                  myInfo == null ? '' : myInfo.signature,
                  style: TextStyle(
                      fontSize: SizeUtil.px(22), color: Color(0xfff3f3f3)),
                ),
              ],
            ),
            SizedBox(
              height: SizeUtil.px(47),
            ),
            Row(
              children: [
                SizedBox(
                  width: SizeUtil.px(27),
                ),
                Text(
                  '关注',
                  style: TextStyle(
                      fontSize: SizeUtil.px(26), color: Color(0xffa5a5a5)),
                ),
                SizedBox(
                  width: SizeUtil.px(18),
                ),
                Text(
                  myInfo == null ? '0' : myInfo.attentions.toString(),
                  style: TextStyle(
                      fontSize: SizeUtil.px(26), color: Color(0xfff3f3f3)),
                ),
                SizedBox(
                  width: SizeUtil.px(100),
                ),
                Text(
                  '粉丝',
                  style: TextStyle(
                      fontSize: SizeUtil.px(26), color: Color(0xffa5a5a5)),
                ),
                SizedBox(
                  width: SizeUtil.px(18),
                ),
                Text(
                  myInfo == null ? '0' : myInfo.fans.toString(),
                  style: TextStyle(
                      fontSize: SizeUtil.px(26), color: Color(0xfff3f3f3)),
                ),
              ],
            ),
            SizedBox(
              height: SizeUtil.px(47),
            ),
            Container(
              width: size.width,
              height: SizeUtil.px(1),
              decoration: BoxDecoration(
                color: Color(0xffffffff),
              ),
            ),
            SizedBox(
              height: SizeUtil.px(42),
            ),
            Align(
              alignment: Alignment.topLeft,
              child: Padding(
                padding: EdgeInsets.only(left: SizeUtil.px(27)),
                child: Text(
                  '贡献榜',
                  style: TextStyle(
                      fontSize: SizeUtil.px(35), color: Color(0xfff3f3f3)),
                ),
              ),
            ),
            SizedBox(
              height: SizeUtil.px(36),
            ),
            Container(
                width: SizeUtil.px(696),
                height: SizeUtil.px(200),
                decoration: BoxDecoration(
                  borderRadius:
                      BorderRadius.all(Radius.circular(SizeUtil.px(16))),
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [Color(0xffe62d6c), Color(0xffff5f6e)],
                  ),
                ),
                child: personContributeEntity != null
                    ? personContributeEntity.length > 0
                        ? isAuth
                            ? ListView.builder(
                                itemCount: personContributeEntity == null
                                    ? 0
                                    : personContributeEntity.length,
                                scrollDirection: Axis.horizontal,
                                controller: _scrollController,
                                shrinkWrap: true,
                                itemBuilder: (context, index) {
                                  return InkWell(
                                    child: PersonContribute(
                                      personContributeEntity:
                                          personContributeEntity[index],
                                    ),
                                    onTap: () {
                                      joinHome( personContributeEntity[
                                      index]
                                          .userId);

                                    },
                                  );
                                },
                              )
                            : Center(
                                child: Text(
                                  '别人的隐私需要保护的哦',
                                  style: TextStyle(color: Color(0xfff3f3f3)),
                                ),
                              )
                        : Center(
                            child: Text(
                              '暂未开启贡献榜',
                              style: TextStyle(color: Color(0xfff3f3f3)),
                            ),
                          )
                    : Center(
                        child: Text(
                          '暂未开启贡献榜',
                          style: TextStyle(color: Color(0xfff3f3f3)),
                        ),
                      )),
            SizedBox(
              height: SizeUtil.px(49),
            ),
            Align(
              alignment: Alignment.topLeft,
              child: Padding(
                padding: EdgeInsets.only(left: SizeUtil.px(27)),
                child: Text(
                  '个人信息',
                  style: TextStyle(
                      fontSize: SizeUtil.px(36), color: Color(0xfff3f3f3)),
                ),
              ),
            ),
            SizedBox(
              height: SizeUtil.px(2),
            ),
            Row(
              children: [
                SizedBox(
                  width: SizeUtil.px(27),
                ),
                Text(
                  '年龄:',
                  style: TextStyle(
                      fontSize: SizeUtil.px(26), color: Color(0xffa5a5a5)),
                ),
                SizedBox(
                  width: SizeUtil.px(6),
                ),
                Text(
                  myInfo == null ? '0' : myInfo.age.toString(),
                  style: TextStyle(
                      fontSize: SizeUtil.px(29), color: Color(0xffe1e1e1)),
                ),
                SizedBox(
                  width: SizeUtil.px(59),
                ),
                Text(
                  '生日:',
                  style: TextStyle(
                      fontSize: SizeUtil.px(26), color: Color(0xffa5a5a5)),
                ),
                SizedBox(
                  width: SizeUtil.px(6),
                ),
                Text(
                  myInfo == null ? '0' : myInfo.birthday,
                  style: TextStyle(
                      fontSize: SizeUtil.px(29), color: Color(0xffe1e1e1)),
                ),
              ],
            ),
            SizedBox(
              height: SizeUtil.px(47),
            ),
            Container(
              width: size.width,
              color: Color(0xff2b244d),
              child: Row(
                children: [
                  SizedBox(
                    width: SizeUtil.px(55),
                  ),
                  Container(
                    width: SizeUtil.px(100),
                    child: IconTextButton.icon(
                      icon: Image.asset(
                        'assets/images/kefu_logo.png',
                        width: SizeUtil.px(35.71),
                        height: SizeUtil.px(36.88),
                      ),
                      label: Text(
                        "客服",
                        style: TextStyle(
                            fontSize: SizeUtil.px(20),
                            color: Color(0xfff3f3f3)),
                      ),
                      color: Color(0xff2b244d),
                      textColor: Color(0xfff3f3f3),
                      elevation: 1.0,
                      disabledElevation: 0,
                      iconTextAlignment: IconTextAlignment.iconTopTextBottom,
                      onPressed: () {},
                    ),
                  ),
                  // SizedBox(width: SizeUtil.px(47),),
                  // Container(
                  //   width: SizeUtil.px(200),
                  //   height: SizeUtil.px(68),
                  //   decoration: BoxDecoration(
                  //     borderRadius: BorderRadius.all(Radius.circular(SizeUtil.px(32))),
                  //     gradient: LinearGradient(
                  //       begin: Alignment.centerLeft,
                  //       end: Alignment.centerRight,
                  //       colors: [Color(0xffff0865), Color(0xfffe7b71)],
                  //     ),
                  //   ),
                  //   child: Center(
                  //     child:  Row(
                  //       mainAxisAlignment: MainAxisAlignment.center,
                  //       children: [
                  //         Image.asset('assets/images/comment_icon.png',width: SizeUtil.px(30.15),height: SizeUtil.px(29.76),),
                  //         SizedBox(width: SizeUtil.px(11),),
                  //         InkWell(
                  //           child: Text('私信',style: TextStyle(fontSize: SizeUtil.px(29),color: Color(0xfff3f3f3))),
                  //           onTap: (){
                  //             Navigator.pop(context);
                  //           },
                  //         )
                  //
                  //       ],
                  //     ),
                  //   ),
                  // ),
                  SizedBox(
                    width: SizeUtil.px(46),
                  ),
                  InkWell(
                    child: Container(
                      width: SizeUtil.px(400),
                      height: SizeUtil.px(68),
                      decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.all(Radius.circular(SizeUtil.px(32))),
                        gradient: LinearGradient(
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                          colors: [Color(0xff13e1ee), Color(0xff5eeb82)],
                        ),
                      ),
                      child: Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              'assets/images/follow_icon.png',
                              width: SizeUtil.px(30.15),
                              height: SizeUtil.px(29.76),
                            ),
                            SizedBox(
                              width: SizeUtil.px(11),
                            ),
                            isAuth
                                ? Text('无法关注自己',
                                    style: TextStyle(
                                        fontSize: SizeUtil.px(29),
                                        color: Color(0xfff3f3f3)))
                                : isFollowed
                                    ? Text('已关注',
                                        style: TextStyle(
                                            fontSize: SizeUtil.px(29),
                                            color: Color(0xfff3f3f3)))
                                    : Text('关注',
                                        style: TextStyle(
                                            fontSize: SizeUtil.px(29),
                                            color: Color(0xfff3f3f3))),
                          ],
                        ),
                      ),
                    ),
                    onTap: () {
                      attentionAnchor().then((value) => () {
                            setState(() {
                              isFollowed = true;
                            });
                          });
                    },
                  )
                ],
              ),
            )
          ],
        ),
    );
  }

  ///关注主播
  Future<void> attentionAnchor() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = AttentionRoomRequest();
    request
        .add('user_id', myInfo.userId1)
        .add('type', 2)
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == 0) {
      TxUtils.showToast(result['data'], context);
    } else if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else {
      TxUtils.showToast(result['message'], context);
    }
  }

  ///是否关注主播
  isAttention() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = AttentionAnchorRequest();
    request.add('anchor_id', myInfo.userId1).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == 0) {
      setState(() {
        isFollowed = result['data'];
      });
    } else if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else {
      TxUtils.showToast(result['message'], context);
    }
  }

  getMyUserInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    if (widget.userId != null) {
      request
          .add('type', 2)
          .add('user_id', widget.userId)
          .addHeader('usertoken', appToken);
    } else {
      request.add('type', 2).addHeader('usertoken', appToken);
    }
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      myInfo = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
      if (widget.userInfoEntity.userId1 == myInfo.userId1) {
        isAuth = true;
      } else {
        isAuth = false;
      }
      isAttention();
    });
  }

  getPersonContribute() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = PersonContributeRequest();
    request.add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      List<Map<String, dynamic>> listMap =
          new List<Map<String, dynamic>>.from(result['data']);
      List<PersonContributeEntity> list = List();
      for (int i = 0; i < listMap.length; i++) {
        list.add(PersonContributeEntity.fromJson(listMap[i]));
      }
      setState(() {
        personContributeEntity = list;
      });
    }
  }

  Future<void> joinHome(int userId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = JoinHomeRequest();
    request.add('join_id', userId).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      if(result['data']){
        Navigator.of(context).push(
            MaterialPageRoute(
                builder: (context) =>
                    UserPersonalInterfacePage(
                      userInfoEntity:
                      widget.userInfoEntity,
                      userId:
                      userId,
                    )));
      }else{
        TxUtils.showErrorToast('对方未开放个人主页', context);
      }
    }
  }
}
